package model

import (
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	CompanyProjectModel interface {
		Insert(company Company) (err error)
		FindOne(company Company) (Company, error)
		Update(company Company) (err error)
		DeleteSoft(company Company) (err error)
		Delete(company Company) (err error)
	}

	DefaultCompanyProjectModel struct {
		conn  *gorm.DB
		table string
	}

	Company struct {
		Company_id   int       `db:"company_id"  json:"company_id"`
		Company_name string    `db:"company_name"  json:"company_name"`
		Create_time  time.Time `db:"create_time"  json:"create_time"`
		Delete_time  time.Time `db:"delete_time"  json:"delete_time"`
		DelState     int       `db:"del_state"  json:"del_state"`
	}
)

func NewDefaultCompanyProjectModel(conn *gorm.DB) *DefaultCompanyProjectModel {
	return &DefaultCompanyProjectModel{
		conn:  conn,
		table: "company",
	}
}

func (com *DefaultCompanyProjectModel) Insert(company Company) (err error) {
	company.Create_time = time.Now()
	company.Delete_time = time.Unix(0, 0)
	com.conn.Create(&company)
	return err
}

func (com *DefaultCompanyProjectModel) FindOne(company Company) (Company, error) {
	var err error
	var count int64
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return Company{}, err
	}
	com.conn.Where("company_id=?", company.Company_id).First(&company)

	return company, nil
}

func (com *DefaultCompanyProjectModel) Update(company Company) (err error) {

	var count int64
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Updates(&company)
	return nil
}

func (com *DefaultCompanyProjectModel) DeleteSoft(company Company) (err error) {
	company.Delete_time = time.Now()
	company.DelState = 1
	var count int64
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	err = com.Update(company)
	if err != nil {
		return err
	}
	return nil
}

func (com *DefaultCompanyProjectModel) Delete(company Company) (err error) {
	var count int64
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	com.conn.Model(&company).Where("company_id=?", company.Company_id).Delete(&company)
	return nil
}
